import { randomToken,unioformDateTransform} from '../../utils/index.js';
import {handleSql} from '../../database/mysql/index.js'

class userLoginStatusModel {
    constructor() {
        this.tableName = 'user_login_status';
    }
    
    // 获取用户登录状态
    async getUserLoginStatus(token) {
        let currentTime = unioformDateTransform(new Date())
        const sql = `SELECT * FROM ${this.tableName} 
                     WHERE token = '${token}'`
        let searchResult =  await handleSql(sql)
        let result =  searchResult.filter(item=>{
            return  (new Date(currentTime).getTime() < new Date(item.expiredTime).getTime()) 
        })
        return result[0]
    }


    // 添加新的用户状态
    async addUserLoginStatus(param) {
        let date = unioformDateTransform(new Date())
        let token = randomToken()
        let expiredTime = unioformDateTransform(new Date(date).getTime() + 20*60*1000)
        const {id:userId,userName} = param
        const sql = `INSERT INTO ${this.tableName}(userId,loginTime,token,expiredTime,userName) 
                     VALUES (?,?,?,?,?)`
        let addResult = await handleSql(sql,[userId,date,token,expiredTime,userName])
        if(addResult.affectedRows == 1){
            return {token,loginDate: date};
        }else{
            return {}
        }
        
    }


    // 更新用户登录状态
    async updateUserLoginStatus(token, statusData) {
        const sql = `UPDATE ${this.tableName} SET ? WHERE token = ?`
        let result =  await handleSql(sql,[statusData,token])
        if(result.affectedRows == 1){
            return true
        }else{
            return false
        }
    }  
}   

export default new userLoginStatusModel();